from django.http import HttpResponseBadRequest
from django.shortcuts import *
from django.views import *
from home.models import *
from django.core.paginator import Paginator,PageNotAnInteger

from django.db.models import Count

# 首页
class IndexView(View):
    def get(self, request):
        #1、获取所有的文字分类数据
        categories  = ArticleCategory.objects.all()
        # 2、获取被选中的类型id
        cat_id = request.GET.get('cat_id',1)
        #3、根据被选中的id获取被选中的文字类型
        try:
            category = ArticleCategory.objects.filter(id=cat_id).first()
        except ArticleCategory.DoesNotExist:  #如果没有查询到指定数据，那么就是用默认值
            return HttpResponseRedirect('此分类信息不存在')
        # 5、根据分类信息查询该分类下的所有文章数据
        articles = Article.objects.filter(category=category)
        #4、获取页面请求传递的页码，页容量
        page_index = request.GET.get('page_index',1) #页码
        page_size = request.GET.get('page_size',2)  #页容量
        #6、使用Django的分页器
        pages = Paginator(articles, page_size) #对查询到的数据对象articles进行分页，设置超过指定页容量就分页
        try:
            list = pages.page(page_index)#获取当前页面的记录
        except PageNotAnInteger:
            list = pages.page(1)#如果用户输入的页面不是整数时，显示第1页的内容

        comments = Comment.objects.all().values('article_id').annotate(artic_id=Count('article_id')).order_by('-artic_id')[:2]
        comm_li = []
        for co in comments:
            # 通过字典拿值条件查询找到博客数据
            comm = Article.objects.filter(id=co['article_id'])
            comm_li.append(comm)
        new_a = Article.objects.order_by('-create_time')[:1]
        contxt = {
            'categories':categories,
            'category':category,
            'articles':list,
            'cat_id':cat_id,
            'new_a':new_a,
            'comm_li': comm_li,
        }
        resp = render(request, 'index.html', context=contxt)
        resp.set_cookie('cat_id',cat_id)
        return resp

#详情
class DetailsView(View):
    def get(self,request):
        art_id=request.GET.get('artid')
        try:
            article = Article.objects.get(id=art_id)
        except Article.DoesNotExist:
            return render(request,'404.html')
        article.total_views += 1
        article.save()

        comm = Comment.objects.filter(article=article).order_by('-created_time')

        for i in comm:
            print(i.user.avatar)
        corrtags = Article.objects.filter(tags=article.tags).order_by('?')[:3]
        # comments = Comment.objects.all().order_by('-artic_id')[:2]
        comm_li = []
        # print(comments)
        # for co in comments:
            # 通过字典拿值条件查询找到博客数据
            # comm = Article.objects.filter(id=co['article_id'])
            # comm_li.append(comm)

        context={
            "article":article,
            'comms': comm,
            'corrtags':corrtags,
            'comm_li': comm_li
        }
        return render(request, 'details.html', context=context)

    def post(self,request):
        #获取用户信息
        user = request.user
        #判断用户是否登录
        if user and user.is_authenticated:
            #接收数据
            art_id = request.POST.get('art_id')
            content = request.POST.get('content')
            #判断文章是否存在
            try:
                art = Article.objects.get(id=art_id)
            except Article.DoesNotExist:
                return HttpResponseBadRequest('没有此文章')
            #保存到数据库
            Comment.objects.create(content=content,article=art,user=user)
            #修改文章评论数量
            art.comments_count += 1
            art.save()
            #拼接跳转路由
            req_url = request.path +'?artid=' +art_id
            return redirect(req_url)
        else:
            #没有登录则跳转到登录页面
            return redirect(reverse('users:login'))



